#include "StdAfx.h"
#include "ChSSettings.h"

CChSSettings* CChSSettings::s_pInstance = NULL;

CChSSettings::CChSSettings(void)
{
	m_strHostName = _T("0.0.0.0");
	m_uPort = 21000;
}

CChSSettings::~CChSSettings(void)
{
}

CChSSettings* CChSSettings::Instance()
{
	return s_pInstance;
}

BOOL CChSSettings::Initialize()
{
	if(NULL == s_pInstance)
		s_pInstance = new CChSSettings;

	return s_pInstance->ReadSetings();
}

void CChSSettings::Uninitialize()
{
	if(NULL != s_pInstance)
	{
		s_pInstance->SaveSettings();
		delete s_pInstance;
		s_pInstance = NULL;
	}
}

BOOL CChSSettings::ReadSetings()
{
	try
	{
		CFile _file;
		if(TRUE == _file.Open(SERVER_SETTINGS_FILE_NAME,CFile::modeRead))
		{
			CArchive _arch(&_file,CArchive::load);
			Serialize(_arch);
			_arch.Close();
			_file.Close();
			return TRUE;
		}
		else
		{
			AfxMessageBox(_T("Can't find file with settings. Use default settings."));
			return FALSE;
		}
	}
	catch (CMemoryException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use default settings."));
		return FALSE;
	}
	catch (CFileException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use default settings."));
		return FALSE;
	}
	catch (CException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use default settings."));
		return FALSE;
	}
}

BOOL CChSSettings::SaveSettings()
{
	try
	{
		CFile _file;
		if(TRUE == _file.Open(SERVER_SETTINGS_FILE_NAME,CFile::modeWrite|CFile::modeCreate))
		{
			CArchive _arch(&_file,CArchive::store);
			Serialize(_arch);
			_arch.Close();
			_file.Close();
			return TRUE;
		}
		else
		{
			AfxMessageBox(_T("Can't find file with settings. Use default settings."));
			return FALSE;
		}
	}
	catch (CMemoryException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use default settings."));
		return FALSE;
	}
	catch (CFileException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use default settings."));
		return FALSE;
	}
	catch (CException* e)
	{
		e->ReportError();
		AfxMessageBox(_T("Can't find file with settings. Use default settings."));
		return FALSE;
	}
}

void CChSSettings::Serialize(CArchive &ar)
{
	if(ar.IsLoading())
	{
		ar>>m_strHostName;
		ar>>m_uPort;
	}
	else
	{
		ar<<m_strHostName;
		ar<<m_uPort;
	}
}